package top.codedance.iotp.client.plugins.sync.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.client.ClientApplication;
import top.codedance.iotp.common.executer.SyncAbstractExecuter;
import top.codedance.iotp.common.entity.PluginResultEntity;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ClientPluginsParamsSetExecuterImpl extends SyncAbstractExecuter {

    @Override
    public PluginResultEntity exec(byte[] data, String taskId) {
        PluginResultEntity result = new PluginResultEntity();
        try {
            String body = new String(data, StandardCharsets.UTF_8);
            JSONObject jo = JSON.parseObject(body);
            Map<String, Map<String, String>> params = new HashMap<>();
            Set<Map.Entry<String, Object>> entries = jo.entrySet();
            for(Map.Entry<String, Object> item : entries){
                String key = item.getKey();
                JSONObject subJo = jo.getJSONObject(key);
                Map<String, String> subParams = new HashMap<>();
                Set<Map.Entry<String, Object>> subEntries = subJo.entrySet();
                for(Map.Entry<String, Object> subItem : subEntries){
                    String subKey = subItem.getKey();
                    String subValue = (String)subItem.getValue();
                    subParams.put(subKey, subValue);
                }
                params.put(key, subParams);
            }
            ClientApplication.saveConfig(params);
            result.setOk(true);
            result.setContext("Success");
        }catch (Exception ex){
            result.setOk(false);
            result.setMsg(ex.getMessage());
        }
        return result;
    }
}
